import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Plus, Edit, Trash2, GripVertical } from 'lucide-react';

const SpecificationEditor = ({ specifications = [], onSpecificationsChange }) => {
  const [editingIndex, setEditingIndex] = useState(-1);
  const [editForm, setEditForm] = useState({ key: '', value: '' });

  // 添加规格
  const handleAddSpecification = () => {
    if (editForm.key.trim() && editForm.value.trim()) {
      const newSpec = {
        id: Date.now(),
        key: editForm.key.trim(),
        value: editForm.value.trim(),
        sort_order: specifications.length
      };
      
      const updatedSpecs = [...specifications, newSpec];
      onSpecificationsChange && onSpecificationsChange(updatedSpecs);
      setEditForm({ key: '', value: '' });
    }
  };

  // 开始编辑
  const handleStartEdit = (index) => {
    setEditingIndex(index);
    setEditForm({
      key: specifications[index].key,
      value: specifications[index].value
    });
  };

  // 保存编辑
  const handleSaveEdit = () => {
    if (editForm.key.trim() && editForm.value.trim()) {
      const updatedSpecs = [...specifications];
      updatedSpecs[editingIndex] = {
        ...updatedSpecs[editingIndex],
        key: editForm.key.trim(),
        value: editForm.value.trim()
      };
      
      onSpecificationsChange && onSpecificationsChange(updatedSpecs);
      setEditingIndex(-1);
      setEditForm({ key: '', value: '' });
    }
  };

  // 取消编辑
  const handleCancelEdit = () => {
    setEditingIndex(-1);
    setEditForm({ key: '', value: '' });
  };

  // 删除规格
  const handleDeleteSpecification = (index) => {
    const updatedSpecs = specifications.filter((_, i) => i !== index);
    onSpecificationsChange && onSpecificationsChange(updatedSpecs);
  };

  // 移动规格位置
  const handleMoveSpecification = (fromIndex, toIndex) => {
    const updatedSpecs = [...specifications];
    const [movedSpec] = updatedSpecs.splice(fromIndex, 1);
    updatedSpecs.splice(toIndex, 0, movedSpec);
    
    // 更新排序
    updatedSpecs.forEach((spec, index) => {
      spec.sort_order = index;
    });
    
    onSpecificationsChange && onSpecificationsChange(updatedSpecs);
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>商品规格</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          {/* 添加规格表单 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="space-y-2">
              <Label htmlFor="spec-key">规格名称</Label>
              <Input
                id="spec-key"
                value={editForm.key}
                onChange={(e) => setEditForm(prev => ({ ...prev, key: e.target.value }))}
                placeholder="如：屏幕、处理器、内存"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="spec-value">规格值</Label>
              <Input
                id="spec-value"
                value={editForm.value}
                onChange={(e) => setEditForm(prev => ({ ...prev, value: e.target.value }))}
                placeholder="如：6.7英寸 OLED"
              />
            </div>
            <div className="flex items-end">
              {editingIndex >= 0 ? (
                <div className="flex gap-2">
                  <Button onClick={handleSaveEdit} size="sm">
                    保存
                  </Button>
                  <Button variant="outline" onClick={handleCancelEdit} size="sm">
                    取消
                  </Button>
                </div>
              ) : (
                <Button onClick={handleAddSpecification} size="sm">
                  <Plus className="size-4 me-1" />
                  添加规格
                </Button>
              )}
            </div>
          </div>

          {/* 规格列表 */}
          {specifications.length > 0 && (
            <div className="space-y-2">
              <Label>规格列表</Label>
              <div className="border rounded-lg">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-12">排序</TableHead>
                      <TableHead>规格名称</TableHead>
                      <TableHead>规格值</TableHead>
                      <TableHead className="w-24">操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {specifications.map((spec, index) => (
                      <TableRow key={spec.id || index}>
                        <TableCell>
                          <div className="flex items-center gap-1">
                            <GripVertical className="size-4 text-muted-foreground cursor-move" />
                            <span className="text-sm text-muted-foreground">{index + 1}</span>
                          </div>
                        </TableCell>
                        <TableCell className="font-medium">{spec.key}</TableCell>
                        <TableCell>{spec.value}</TableCell>
                        <TableCell>
                          <div className="flex items-center gap-1">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleStartEdit(index)}
                            >
                              <Edit className="size-3" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleDeleteSpecification(index)}
                              className="text-destructive hover:text-destructive"
                            >
                              <Trash2 className="size-3" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>
          )}

          {/* 规格预览 */}
          {specifications.length > 0 && (
            <div className="space-y-2">
              <Label>规格预览</Label>
              <div className="flex flex-wrap gap-2">
                {specifications.map((spec, index) => (
                  <Badge key={index} variant="secondary" className="text-sm">
                    {spec.key}: {spec.value}
                  </Badge>
                ))}
              </div>
            </div>
          )}

          {/* 空状态 */}
          {specifications.length === 0 && (
            <div className="text-center py-8 text-muted-foreground">
              <p>暂无规格信息</p>
              <p className="text-sm">请添加商品规格参数</p>
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
};

export default SpecificationEditor; 